﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;

namespace Orchard.Test.Library
{
    public class MediaHelp : UIHelperBase
    {
        public MediaHelp(TestLibrary settings) : base(settings){ }   

        public void ManageMediaFolders()
        {
            if (!selenium.GetLocation().EndsWith("/Admin/Media"))
            {
                selenium.Open("/Admin/Media");
            }
        }       

        public void AddMediaFolder(string mediaFolder)
        {
            selenium.Open("/Admin/Media/Create");
            selenium.Type("Name", mediaFolder);
            Submit();
        }

        public void DeleteMediaFolder(string mediaFolder)
        {
            ManageMediaFolders();
            selenium.Check(String.Format("//input[@name='Checkbox.{0}']", mediaFolder));
            Submit();
        }

        public bool IsMediaFolderPresent(string mediaFolder)
        {
            ManageMediaFolders();
            return selenium.IsElementPresent("link=" + mediaFolder);
        }

        public bool IsMediaPresent(string mediaFolder,string mediaName)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", mediaFolder));
            return selenium.IsElementPresent("link=" + mediaName);
        }
    
        public void AddSubMediaFolder(string fatherFolder,string subFolder)
        {
            selenium.Open(String.Format("/Admin/Media/Create?MediaPath={0}", fatherFolder));            
            selenium.Type("Name", subFolder);
            Submit();      
        }

        public void DeleteSubMediaFolder(string fatherFolder, string subFolder)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", fatherFolder));
            selenium.Check(String.Format("//input[@name='Checkbox.Folder.{0}']", subFolder));
            selenium.Select("publishActions", "label=Delete");
            Submit();
        }

        public bool IsSubMediaFolderPresent(string fatherFolder, string subFolder)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", fatherFolder));
            return selenium.IsElementPresent(String.Format("link={0}",subFolder));
        }        

        public void RenameMediaFolder(string folderName, string newFolderName)
        {            
            selenium.Open(String.Format("/Admin/Media/EditProperties?folderName={0}&mediaPath={0}", folderName));
            selenium.Type("Name", newFolderName);
            Submit();
        }       

        public void RenameSubMediaFolder(string fatherFolder, string oldSubFolder, string newSubFolder)
        {
            selenium.Open(String.Format("/Admin/Media/EditProperties?folderName={0}&mediaPath={1}\\{0}", oldSubFolder, fatherFolder));
            selenium.Type("Name", newSubFolder);
            ClickAndWait("//button[@name='submit.Save']"); 
        }        
    
        public void DeleteMediaFolderByProperties(string folderName)
        {         
            selenium.Open(String.Format("/Admin/Media/EditProperties?folderName={0}&mediaPath={0}", folderName));       
            ClickAndWait("//button[@name='submit.Delete']");  
        }

        public void DeleteSubMediaFolderByProperties(string folderName,string parentFolder)
        {
            selenium.Open(String.Format("/Admin/Media/EditProperties?folderName={0}&mediaPath={1}\\{0}", folderName,parentFolder));
            ClickAndWait("//button[@name='submit.Delete']");
        }

        public void UploadMedia(string mediaFolder, string mediaPath)
        {
            UploadMedia(mediaFolder, mediaPath, false);
        }
      
        public void UploadMedia(string mediaFolder, string mediaPath, bool extractZip)
        {
            selenium.Open(String.Format("/Admin/Media/Add?folderName={0}&mediaPath={0}", mediaFolder));     
            selenium.Type("MediaItemPath", mediaPath);
            if (extractZip)
            {
                selenium.Check("ExtractZip");
            }
            else
            {
                selenium.Uncheck("ExtractZip");
            }
            Submit();
        }            

        public void EditMedia(string mediaFolder, string oldMediaName, string newMediaName)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", mediaFolder));
            ClickAndWait("link=" + oldMediaName);           
            selenium.Type("NewName", newMediaName);                   
            Submit();
        }

        public void EditMediaFolder(string mediaFolder)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", mediaFolder));           
        }

        public void DeleteMedia(string mediaFolder, string mediaName)
        {
            selenium.Open(String.Format("/Admin/Media/Edit?name={0}&mediaPath={0}", mediaFolder));
            selenium.Check(String.Format("//input[@name='Checkbox.File.{0}']", mediaName));
            selenium.Select("publishActions", "label=Delete");
            Submit();
        }

        private void OpenPickImageWindow()
        {
            selenium.Click(String.Format("//img[contains(@src,'{0}')]", TestLibrary.Consts.OrchardSite + @"/Modules/TinyMce/scripts/plugins/mediapicker/img/picture_add.png"));
            selenium.WaitForPopUp("_blank", "30000");
            selenium.SelectWindow(selenium.GetAllWindowTitles()[1]);
            selenium.SetSpeed("2000");
        }

        private void OpenBrowseMedia()
        {
            selenium.Click("link=Browse Media");
        }

        private void SetMediaProperties(MediaProperties mediaProperties)
        {
            selenium.Type("img-alt", mediaProperties.AlternativeText);
            selenium.Type("img-class", mediaProperties.Class);
            selenium.Type("img-style", mediaProperties.Style);
            if(mediaProperties.Alignment!=ImageAlign.TextTop)
            selenium.Select("img-align", Enum.GetName(typeof(ImageAlign), mediaProperties.Alignment));
            else if (mediaProperties.Alignment == ImageAlign.TextTop) 
                selenium.Select("img-align", "Text Top");
            if (mediaProperties.LockAspectRatio)
            {
                selenium.Check("img-lock");
            }
            else
            {
                selenium.Uncheck("img-lock");
            }
            selenium.Type("img-width", mediaProperties.Width);
            selenium.Type("img-height", mediaProperties.Height);
            
        }

        public void InsertMediaFromComputer(string mediaPath, MediaProperties mediaProperties)
        {
            OpenPickImageWindow();
            selenium.Type("fileUpload", mediaPath);
            selenium.Click("upload");
            SetMediaProperties(mediaProperties);
            selenium.Click("img-insert");
        }

        public void InsertMediaFromUrl(string pictureUrl)
        {
            OpenPickImageWindow();
            selenium.Type("img-src", pictureUrl);
            selenium.Click("img-insert");
            SetWindowBack();
            Submit();
        }

        public void InsertMediaFromUrlNotSubmit(string pictureUrl, MediaProperties mediaProperties)
        {
            OpenPickImageWindow();
            selenium.Type("img-src", pictureUrl);
            SetMediaProperties(mediaProperties);
            selenium.Click("img-insert");
            SetWindowBack();
            //Submit();
        }
        public void InsertMediaFromUrlAndSubmit(string pictureUrl, MediaProperties mediaProperties)
        {
            OpenPickImageWindow();
            selenium.Type("img-src", pictureUrl);
            SetMediaProperties(mediaProperties);
            selenium.Click("img-insert");
            SetWindowBack();
            Submit();
        }

        public void SetWindowBack()
        {
           selenium.SelectWindow(selenium.GetAllWindowTitles()[0]);
           selenium.SetSpeed("1000");
        }

        public void InsertMediaFromComputerNotSubmit(string mediaPath, MediaProperties mediaProperties)
        {
            InsertMediaFromComputer(mediaPath, mediaProperties);
            SetWindowBack();
        }
       
        public void InsertMediaFromComputerAndSubmit(string mediaPath, MediaProperties mediaProperties)
        {
            InsertMediaFromComputerNotSubmit(mediaPath, mediaProperties);
            Submit();
        }
   
        public void InsertMediaFromGalleryAndSubmit(string folderInGallery)
        {
            OpenPickImageWindow();
            OpenBrowseMedia();
            selenium.Click(String.Format("link={0}", folderInGallery));             
            selenium.Click("//div[@id='file-list']/table/tbody/tr/td[1]");
            selenium.Click("lib-insert");
            SetWindowBack();
            Submit();
        }

        public void CreateMediaFolderToGallery(string mediaFolder)
        {
            OpenPickImageWindow();
            OpenBrowseMedia();
            selenium.Type("folderName", mediaFolder);
            selenium.Click("createFolder");
        }
        public void UploadMediaToGalleryAfterCreateFolder(string mediaFolder, string mediaPath)
        {
            CreateMediaFolderToGallery(mediaFolder);
            System.Threading.Thread.Sleep(5000);
            selenium.Click("link=" + mediaFolder);
            selenium.Type("//form[@id='lib-uploadform']/input[@id='fileUpload']", mediaPath);
            selenium.Click("//form[@id='lib-uploadform']/input[@id='upload']"); 
        }

        public void UploadMdiaFromPickImage(string mediaPath)
        {
            OpenPickImageWindow();
            selenium.Type("//form[@id='img-uploadform']/input[@id='fileUpload']", mediaPath);
            selenium.Click("//form[@id='img-uploadform']/input[@id='upload']"); 
        }

        public void UploadMediaToGallery(string mediaPath, string mediaFolder)
        {
            OpenPickImageWindow();
            OpenBrowseMedia();
            selenium.Click("link=" + mediaFolder);
            selenium.Type("//form[@id='lib-uploadform']/input[@id='fileUpload']", mediaPath);
            selenium.Click("//form[@id='lib-uploadform']/input[@id='upload']"); 
        }
               
    }

    public class MediaProperties
    {
        public string AlternativeText{get; set;}
        public string Class{get;set;}
        public string Style{get; set;}
        public ImageAlign Alignment{get;set;}
        public string Width{get;set;}
        public string Height{get;set;}
        public bool LockAspectRatio{get;set;}

        public MediaProperties()
        {
            LockAspectRatio = true;
        }
    }

    public enum ImageAlign
    {
        None,
        Left,
        Right,
        Top,
        TextTop,
        Middle,
        AbsMiddle,
        Bottom,
        AbsBottom,
        Baseline
    }
}
